#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include "user_threads.h"
#include "publicFunctions.h"



int uthread_open(const char* filename, int flags){
	return open(filename, (flags|O_NONBLOCK));
}

int uthread_pipe(int filedes[2]){
	int i,j;
	i=pipe(filedes);
	if (i==0){
		j=fcntl(filedes[0], F_SETFL, O_NONBLOCK); 
		if(j!=0){
			close(filedes[0]);
			close(filedes[1]);
			return j;
		}
		j=fcntl(filedes[1], F_SETFL, O_NONBLOCK);
		if(j!=0){
			close(filedes[0]);
			close(filedes[1]);
			return j;
		}
		return 0;
	}
	return i;
}

int uthread_read(int fd, void* buf, size_t count){
	int i, err;
	int flag=1;
	while (flag==1){
		flag=0;
		disableSignals();
		i = read(fd, buf,  count);
		err = errno;
		enableSignals();
		if (i==-1 && err==EAGAIN){
			flag=1;
			uthread_yield();
	     	}
	}
	return i;
}

int uthread_write(int fd, const void* buf, size_t count){
	int i, err;
	int flag=1;
	while (flag==1)	{
		flag=0;
		disableSignals();
		i = write(fd, buf,  count);
		err = errno;
		enableSignals();
		if (i==-1 && err==EAGAIN){
		  flag=1;
		  uthread_yield();
	     }
	}
	return i;
}
